/**
 * 全站权限配置
 *
 */
import router from './router/index'
import store from '@/store'
import { validatenull } from '@/util/validate'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false })

router.beforeEach((to, from, next) => {
  // console.log(router)
  // console.log(window.location.href)
  // console.log(window.location.path)
  var cPath = window.location.href
  var tPath = cPath.split("#")[1]; //字符分割
  // console.log(tPath)
  //TODO 页面刷新路由出现404
  if (from.name === null) {
    // console.log(from)
    // console.log(to)
  }
  // 缓冲设置
  if (to.meta.keepAlive === true) {
    to.meta.$keepAlive = true
  } else {
    NProgress.start()
    if (to.meta.keepAlive === true && validatenull(to.meta.$keepAlive)) {
      to.meta.$keepAlive = true
    } else {
      to.meta.$keepAlive = false
    }
  }
  const meta = to.meta || {}
  if (store.getters.access_token) {
    if (store.getters.isLock && to.path !== '/lock') {
      next({ path: '/lock' })
    } else if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (store.getters.roles.length === 0) {
        // console.log('store.getters.menu')
        // console.log(store.getters.menu)
        //var dynamicRoutes = router.$flyrayRouter.formatRoutes(store.getters.menu, true)

        // 请求后台菜单生成动态路由
        store.dispatch('GetMenu').then(data => {
          // 根据roles权限生成可访问的路由表
          // 动态添加可访问路由表
          // console.log('store.getters.addRouters')
          // console.log(store.getters.addRouters)
          router.addRoutes(store.getters.addRouters)
          // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          const redirect = decodeURIComponent(from.query.redirect)
          // console.log("to.path")
          // console.log("redirect")
          // console.log(to.path)
          // console.log(redirect)
          if (to.path === redirect) {
            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            next({ ...to, replace: true })
          } else {
            // 跳转到目的路由
            if (!to.path == "/404" || from.path == "/login") {
              next({ path: to.path, replace: true })
            } else {
              next({ path: tPath, replace: true })
            }

          }

        })

        store.dispatch('GetUserInfo').then(() => {
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({ path: '/login' })
          })
        })

      } else {
        next()
      }
    }

  } else {
    if (meta.isAuth === false) {
      next()
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
